<?php

namespace mpend\modules\demand\models;

use Yii;
use yii\db\Exception;
use common\helpers\Url;
use common\helpers\StringHelper;
use common\helpers\ArrayHelper;
use common\models\demand\Demand;
use common\models\demand\DemandContent;
use common\models\demand\DemandAttach;

/**
 * 需求发布模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class DemandPublishForm extends BaseDemandForm {

    /**
     * @var string 直播ID
     */
    public $category_id;

    /**
     * @var string 签名字符串
     */
    public $title;

    /**
     * @inheritdoc
     */
    public function rules() {
        return ArrayHelper::merge(parent::rules(), [
            [['category_id', 'title'], 'required'],
            [['category_id'], 'integer'],
            [['title'], 'string', 'max' => 255],
        ]);
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return ArrayHelper::merge(parent::attributeLabels(), [
            'category_id' => '分类',
            'title' => '需求标题',
        ]);
    }

    /**
     * 加密流验证操作
     * @inheritdoc
     */
    public function save() {
        if (!$this->validate()) {
            return $this->validateError('');
        }
        //需求
        $model = new Demand();
        $model->setAttributes([
            'user_id' => $this->user_id,
            'category_id' => $this->category_id,
            'title' => $this->title,
            'thumb' => $this->getThumb(),
            'description' => StringHelper::truncate($this->content, 250),
            'status' => Demand::STATUS_ACTIVE
        ]);
        $images = $this->images;
        $attachs = $this->getAttachFiles();
        //需求内容
        $content = new DemandContent();
        $content->body = $this->content;
        //附件保存
        $attachModel = new DemandAttach();
        $attachModel->user_id = $this->user_id;
        //开启事务
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$model->save()) {
                throw new Exception('需求创建失败！');
            }
            $content->demand_id = $model->id;
            $attachModel->demand_id = $model->id;
            if (!$content->save()) {
                throw new Exception('需求内容保存失败！');
            }
            if (!empty($images)) {
                foreach ($images as $image) {
                    $_attach = clone $attachModel;
                    $_attach->format = DemandAttach::FORMAT_IMAGE;
                    $_attach->path = $image;
                    if (!$_attach->save()) {
                        throw new Exception('图片保存失败！');
                    }
                }
            }
            if (!empty($attachs)) {
                foreach ($attachs as $attach) {
                    $_attach = clone $attachModel;
                    $_attach->setAttributes($attach);
                    if (!$_attach->save()) {
                        throw new Exception('附件保存失败！');
                    }
                }
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->dumpError($e->getMessage());
        }
        return [
            'description' => '需求发布成功',
            'image' => '/static/images/blank/success.png',
            'buttons' => [
                [
                    'type' => 'default',
                    'text' => '返回',
                    'mplink' => [
                        'type' => 'back',
                        'route' => 1,
                    ],
                ],
                [
                    'type' => 'info',
                    'text' => '查看需求',
                    'mplink' => [
                        'type' => 'redirect',
                        'route' => Url::to([
                            '/pages/demand/main', 'id' => $model->id
                        ]),
                    ],
                ]
            ],
        ];
    }

}
